package io.dcloud.uniplugin;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import io.dcloud.feature.uniapp.AbsSDKInstance;
import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;
import io.dcloud.uniplugin.bc.EventBusMsg;
import io.dcloud.uniplugin.bc.ScanActivity;
import io.dcloud.uniplugin.bc.TrainActivity;
import io.dcloud.uniplugin.bc.TrainEntryActivity;
import io.dcloud.uniplugin.utils.BluetoothScanMgr;


public class TestModule extends UniModule {

    String TAG = "TestModule";
    public static int REQUEST_CODE = 1000;
    public static AbsSDKInstance myUniSDKInstance = null;


    //run ui thread
    @UniJSMethod(uiThread = true)
    public void testAsyncFunc(JSONObject options, UniJSCallback callback) {
        Log.e(TAG, "testAsyncFunc--" + options);
        if (callback != null) {
            JSONObject data = new JSONObject();
            data.put("code", "success");
            callback.invoke(data);
            //callback.invokeAndKeepAlive(data);
        }
    }

    //run JS thread
    @UniJSMethod(uiThread = false)
    public JSONObject testSyncFunc() {
        JSONObject data = new JSONObject();
        data.put("code", "success");
        return data;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && data.hasExtra("respond")) {
            Log.e("TestModule", "原生页面返回----" + data.getStringExtra("respond"));
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @UniJSMethod(uiThread = true)
    public void gotoNativePage() {
        if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
            Intent intent = new Intent(mUniSDKInstance.getContext(), ScanActivity.class);
            ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
        }
    }


    @UniJSMethod(uiThread = true)
    public void startScan(JSONObject json, UniJSCallback callback) {
        Log.e(TAG, "startScan: ===================> ");
        BluetoothScanMgr mgr = BluetoothScanMgr.getInstance(mUniSDKInstance.getContext(), mUniSDKInstance);
        mgr.startScan(callback);
    }

    @UniJSMethod(uiThread = true)
    public void stopScan(JSONObject json, UniJSCallback callback) {
        Log.e(TAG, "stopScan:===================> ");
        BluetoothScanMgr mgr = BluetoothScanMgr.getInstance(mUniSDKInstance.getContext(), mUniSDKInstance);
        mgr.stopScan(callback);
    }

    @UniJSMethod(uiThread = true)
    public void doConnect(JSONObject json, UniJSCallback callback) {
        Log.e(TAG, "doConnect: ===================> " + json);
        BluetoothScanMgr mgr = BluetoothScanMgr.getInstance(mUniSDKInstance.getContext(), mUniSDKInstance);
        mgr.doConnect(json.get("deviceName").toString());
//        mgr.doConnect("CL1A-909D5");

    }

    @UniJSMethod(uiThread = true)
    public void doDisconnect(JSONObject json, UniJSCallback callback) {
        Log.e(TAG, "doDisconnect: ===================> " + json);
        BluetoothScanMgr mgr = BluetoothScanMgr.getInstance(mUniSDKInstance.getContext(), mUniSDKInstance);
        mgr.doDisconnect();
    }

    @UniJSMethod(uiThread = true)
    public void startGame(JSONObject json, UniJSCallback callback) {
        Log.e(TAG, "startGame:===================>  " + json);
        myUniSDKInstance = mUniSDKInstance;
        BluetoothScanMgr mgr = BluetoothScanMgr.getInstance(mUniSDKInstance.getContext(), mUniSDKInstance);
        try {
            mgr.startGame(Integer.parseInt(json.get("courseId").toString()),
                    Integer.parseInt(json.get("stage").toString()),
                    Boolean.valueOf(json.get("withIntro").toString()),
                    Integer.parseInt(json.get("duration").toString()),
                 // 使用 Boolean.valueOf() 来转换布尔值
                   Integer.parseInt(json.get("bestScore").toString()));
            if (callback != null) {
                JSONObject data = new JSONObject();
                data.put("code", "1");
                data.put("message", "Game Start Success");
                callback.invoke(data);
            }
        } catch (NumberFormatException e) {
            Log.e(TAG, "startGame:===================>  err" + e);

            if (callback != null) {
                JSONObject data = new JSONObject();
                data.put("code", "-1");
                data.put("message", "Game Start Error:"+e.getMessage());
                callback.invoke(data);
            }
        }

//        mgr.startGame(Integer.parseInt(json.get("courseId").toString()), 1, false, 10, 1);
    }

    @UniJSMethod(uiThread = true)
    public void uniToFront(JSONObject json, UniJSCallback callback) {
        Log.e(TAG, "uniToFront:===================>  " + json);
        Intent intent = new Intent();
        intent.setClassName("com.ningshenbao", "io.dcloud.PandoraEntry");
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        mUniSDKInstance.getContext().startActivity(intent);
    }

    @UniJSMethod(uiThread = true)
    public void gameToFront(JSONObject json, UniJSCallback callback) {
        Log.e(TAG, "gameToFront:===================>  " + json);
        Intent intent = new Intent(mUniSDKInstance.getContext(), TrainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        mUniSDKInstance.getContext().startActivity(intent);
    }

    @UniJSMethod(uiThread = true)
    public void openActivity(JSONObject json, UniJSCallback callback) {
        Log.e(TAG, "openActivity:===================>  " + json);
        // 保存SDK实例引用，以便在uniFrontActivity中使用
        myUniSDKInstance = mUniSDKInstance;
        Intent intent = new Intent(mUniSDKInstance.getContext(), uniFrontActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        mUniSDKInstance.getContext().startActivity(intent);
        
        if (callback != null) {
            JSONObject data = new JSONObject();
            data.put("code", "success");
            data.put("message", "已打开uniFrontActivity");
            callback.invoke(data);
        }
    }

    @UniJSMethod(uiThread = true)
    public void getDeviceVersion(JSONObject json, UniJSCallback callback) {
        String brand= Build.MANUFACTURER;//制造商  HUAWEI
        String device_model=Build.MODEL;//设备名称（型号代码）    AGS6-W10
        String system_version=Build.VERSION.RELEASE;//安卓系统版本   10
        String zengliang_version=Build.VERSION.INCREMENTAL;//增量版本   103.0.0.110C00
        String app_version = getAppVersionName(mUniSDKInstance.getContext());//当前App版本号

        if (callback != null) {
            JSONObject data = new JSONObject();
            data.put("brand", brand);
            data.put("device_model",device_model);
            data.put("system_version",system_version);
            data.put("zengliang_version",zengliang_version);
            data.put("app_version", app_version);
            callback.invoke(data);
        }
    }
    
    /**
     * 获取当前App版本号
     */
    private String getAppVersionName(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "获取App版本号失败: " + e.getMessage());
            return "未知版本";
        }
    }
}
